<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="main-content">
    <commonGlassCard width="270" height="270" style="user-select: none;" id="avatar">
      <img :src="getAvatarUrl || defaultAvatar" class="user-avatar" />
    </commonGlassCard>
    <commonGlassCard id="info" width="350" height="508" class="profile-container" style="user-select: none;">
      <!-- 用户信息表单 -->
      <el-form label-width="100px" class="profile-form">
        <el-form-item v-for="(item, index) in test" :label="item.label" :key="index">
          <el-input class="info-input" :value="getUserField(item.model)" disabled></el-input>
        </el-form-item>
      </el-form>
    </commonGlassCard>
    <commonGlassCard id="gt" width="180" height="180" style="user-select: none;" @click="showAvatarChange = true">
      <img style="height: 180px; width: 180px; cursor: pointer; -webkit-user-drag: none;" src="@/assets/changeAvatar.svg">
      <p style="color: #425aef; position: relative; bottom: 42px; left: 42px;">更换头像</p>
    </commonGlassCard>
    <commonGlassCard id="gx" width="180" height="180" style="user-select: none; -webkit-user-drag: none;" @click="showInfoChange = true">
      <img style="height: 136px; width: 136px; margin: 22px; cursor: pointer;" src="@/assets/changeInfo.svg">
      <p style="color: #425aef; position: relative; bottom: 42px; left: 42px;">修改信息</p>
    </commonGlassCard>
    <commonGlassCard id="gm" width="180" height="180" style="user-select: none; -webkit-user-drag: none;" @click="showPwdChange = true">
      <img style="height: 120px; width: 120px; margin: 30px; cursor: pointer;" src="@/assets/changePwd.svg">
      <p style="color: #425aef; position: relative; bottom: 42px; left: 42px;">重置密码</p>
    </commonGlassCard>
    <commonGlassCard id="weather" width="428" height="250">
      <img src="https://api.vvhan.com/api/ipCard?tip=Hello 欢迎使用" style="-webkit-user-drag: none;">
    </commonGlassCard>
    <commonGlassCard width="720" height="450" id="fj1"  style="user-select: none; -webkit-user-drag: none;">
      <img src="https://api.vvhan.com/api/wallpaper/views" style="height: 100%;width: 100%;">
    </commonGlassCard>
    <commonGlassCard width="580" height="180" id="gr">
      <p style="color: #000;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;font-size: 42px;">个 人 信 息</p>
    </commonGlassCard>
    <!-- 更换头像dialog -->
    <el-dialog v-model="showAvatarChange" width="246" draggable :show-close="false">
      <template #header>
        <div class="custom-title">上传图片以替换</div>
      </template>
      <AvatarUploader @upload-success="handleAvatarUploadSuccess" />
    </el-dialog>
    <!-- 修改资料对话框 -->
    <el-dialog v-model="showInfoChange" width="400px" draggable :show-close="false">
      <template #header>
        <div class="custom-title">修改详细信息</div>
      </template>
      <el-form ref="infoForm" :model="userInfo" label-width="70px" :rules="rules" class="info-form">
        <el-form-item v-for="(item, key) in formItems" :key="key" :label="item.label" :prop="item.prop">
          <el-input v-model="userInfo[item.prop]" :placeholder="`请输入${item.label}`" :type="item.type"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改密码dialog -->
    <el-dialog v-model="showPwdChange" width="400px" draggable :show-close="false">
      <template #header>
        <div class="custom-title">修改密码</div>
      </template>
      <el-form ref="passwordForm" :model="passwordForm" :rules="pwdRules" label-width="100px">
        <el-form-item v-for="(item, index) in pwdItems" :key="index" :label="item.label" :prop="item.prop">
          <el-input v-model="passwordForm[item.prop]" type="password" :placeholder="item.placeholder" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitNewPwd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { layout } from '@/utils/layout'
import commonGlassCard from '@/components/commonGlassCard'
import AvatarUploader from '../common/AvatarUploader'
import axios from 'axios'
import axiosService from '@/utils/request'
import { showMsg } from '@/utils/showMsg'

export default {
  components: {
    commonGlassCard,
    AvatarUploader
  },

  data()
  {
    return {
      // 默认头像
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',

      // 用户基本信息（从 Vuex 获取的初始值）
      userInfo: {
        nickname: '',
        email: '',
        tel: '',
        xuexiao: '',
        xueyuan: '',
        zhuanye: '',
        xuehao: ''
      },
      formItems: [
        { label: '昵称', prop: 'nickname', type: 'text' },
        { label: '邮箱', prop: 'email', type: 'email' },
        { label: '手机号', prop: 'tel', type: 'tel' },
        { label: '学校', prop: 'xuexiao', type: 'text' },
        { label: '学院', prop: 'xueyuan', type: 'text' },
        { label: '专业', prop: 'zhuanye', type: 'text' },
        { label: '学号', prop: 'xuehao', type: 'text' }
      ],

      // 修改密码相关
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      pwdItems: [
        { label: '旧密码', prop: 'oldPassword', placeholder: '请输入旧密码' },
        { label: '新密码', prop: 'newPassword', placeholder: '请输入新密码' },
        { label: '确认密码', prop: 'confirmPassword', placeholder: '请再次输入新密码' }
      ],
      pwdRules: {
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ]
      },

      // 表单验证规则
      rules: {
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        xuexiao: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
        xueyuan: [{ required: true, message: '请输入学院名称', trigger: 'blur' }],
        zhuanye: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
        xuehao: [{ required: true, message: '请输入学号', trigger: 'blur' }]
      },

      // 对话框显示状态
      showAvatarChange: false,
      showInfoChange: false,
      showPwdChange: false
    }
  },

  computed: {
    // 获取头像 URL，优先使用 Vuex 中的值，fallback 到默认头像
    getAvatarUrl()
    {
      return this.$store.state.user?.avatar || this.defaultAvatar
    }
  },

  created()
  {
    this.test = [
      { label: '昵称', model: 'nickname' },
      { label: '账号', model: 'account' },
      { label: '邮箱', model: 'email' },
      { label: '电话', model: 'tel' },
      { label: '学校', model: 'xuexiao' },
      { label: '学院', model: 'xueyuan' },
      { label: '专业', model: 'zhuanye' },
      { label: '学号', model: 'xuehao' },
      { label: '注册时间', model: 'registerTime' },
      { label: '您已使用智柜', model: 'duration' }
    ]
    this.checkUserInfo()
  },

  mounted()
  {
    this.updateUserInfo()
  },

  methods: {
    onLayout()
    {
      layout(this)
    },

    // 检查 Vuex 中的用户信息是否有效
    checkUserInfo()
    {
      if (!this.$store.state.user || !this.$store.state.user.id)
      {
        showMsg('登录状态失效', '请重新登录', 'warning')
        this.handleLogout()
        return
      }
      this.updateUserInfo()
    },

    // 获取用户特定字段，处理 Vuex 状态为空的情况
    getUserField(field)
    {
      return this.$store.state.user?.[field] || '未设置'
    },

    // 更新用户信息
    updateUserInfo()
    {
      if (!this.$store.state.user?.id)
      {
        this.handleLogout()
        return
      }

      axios.get(`/node/users/id/${this.$store.state.user.id}`)
        .then(res =>
        {
          const obj = res.data.data
          if (obj)
          {
            // 更新 Vuex 状态和本地 userInfo
            this.$store.commit('updateUser', obj)
            for (const key in this.userInfo)
              this.userInfo[key] = obj[key] || ''
          }
          else
            this.handleLogout()
        })
        .catch(e =>
        {
          showMsg('网络错误', '用户信息加载失败，请重新登录', 'error')
          this.handleLogout()
        })
    },

    // 处理头像上传成功
    handleAvatarUploadSuccess(avatarUrl)
    {
      axios.post('/node/users/uploadAvatar', {
        id: this.$store.state.user?.id,
        avatarUrl
      })
        .then(() =>
        {
          this.updateUserInfo()
          showMsg('数据库更新成功', '', 'success')
          this.showAvatarChange = false // 关闭对话框
        })
        .catch(e =>
        {
          showMsg('头像更新失败', e, 'error')
        })
    },

    // 提交修改用户信息
    submitForm()
    {
      this.$refs.infoForm.validate((valid) =>
      {
        if (valid)
        {
          axiosService.post(`/node/users/updetails/${this.$store.state.user?.id}`, this.userInfo)
            .then(() =>
            {
              this.updateUserInfo()
              showMsg('更新成功', '个人详细信息已重置', 'success')
              this.showInfoChange = false // 关闭对话框
            })
            .catch(e =>
            {
              showMsg('更新失败', e, 'error')
              window.location.reload()
            })
        }
        else
          showMsg('表单非法', '表单验证失败，请检查输入内容', 'error')
      })
    },

    // 提交新密码
    submitNewPwd()
    {
      this.$refs.passwordForm.validate((valid) =>
      {
        if (valid)
        {
          axiosService.post(`/node/users/resetPwd/${this.$store.state.user?.id}`, this.passwordForm)
            .then(res =>
            {
              showMsg(res.data, '请重新登录', 'success')
              this.handleLogout() // 重置密码后退出登录
            })
            .catch(e =>
            {
              showMsg('密码重置失败', e, 'error')
            })
        }
        else
          showMsg('表单非法', '表单验证失败，请检查输入内容', 'error')
      })
    },

    // 验证新密码和确认密码是否一致
    validatePassword(rule, value, callback)
    {
      if (value !== this.passwordForm.newPassword)
      
        callback(new Error('两次输入的密码不一致'))
      
      else
      
        callback()
    },

    // 处理登出逻辑
    handleLogout()
    {
      // 清除 Vuex 状态
      this.$store.commit('logout')
      // 跳转到登录页面
      layout(this, true, '请重新登录')
    }
  }
}
</script>

<style scoped>
.main-content {
  height: calc(100vh - 100px);
  overflow: hidden;
  margin-left: 100px;
}
#gt {
  position: absolute;
  bottom: 185px;
  right: 397px;
}
#gx {
  position: absolute;
  bottom: 0;
  right: 397px;
}
#gm {
  position: absolute;
  bottom: 370px;
  right: 397px;
}
#fj1 {
  position: absolute;
  bottom: 0;
  right: 592px;
}
#gr {
  display: flex;justify-content: center;align-items: center;
  position: absolute;
  bottom: 555px;
  right: 0;
}
#info {
  position: absolute;
  right: 0;
  bottom: 0;
}
#weather {
  position: absolute;
  right: 600px;
  bottom: 480px;
}

.profile-container {
  max-width: 500px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 12px;
}

.info-input {
  width: 200px;
}

.user-avatar {
  border-radius: 12px;
  width: 270px;
  height: 270px;
  background-size: cover;
  background-position: center;
  -webkit-user-drag: none;
}
.custom-title {
  font-size: 30px;
  font-weight: 600;
  color: #858585;
  text-align: center;
}
.info-form {
  width: 100%;
}

.custom-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
